package com.ehouse.widgets;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.Loader.OnLoadCompleteListener;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.ehouse.R;
import com.ehouse.connection.ConnectionService;
import com.ehouse.connection.ConnectionService.IConnectionResponseListener;
import com.ehouse.database.LightTable;
import com.ehouse.models.Settings;

public class LightsWidget extends AppWidgetProvider {

	private static final String ACTION_TAG = "ACTION";
	private static Context gContext;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		gContext = context;
		Log.d("LightsWidget", "onUpdate ids: " + Arrays.toString(appWidgetIds));

		final int n = appWidgetIds.length;
		for (int i = 0; i < n; i++) {
			final int appWidgetId = appWidgetIds[i];

			Uri data = Uri.withAppendedPath(Uri.parse("lightson://widget/id/"),
					String.valueOf(appWidgetId));
			Intent onIntent = new Intent(context, LightsUpdater.class);
			onIntent.setData(data);
			onIntent.putExtra(ACTION_TAG, 1);

			data = Uri.withAppendedPath(Uri.parse("lightsoff://widget/id/"),
					String.valueOf(appWidgetId));
			Intent offIntent = new Intent(context, LightsUpdater.class);
			offIntent.setData(data);
			offIntent.putExtra(ACTION_TAG, 0);

			PendingIntent on = PendingIntent.getBroadcast(context, 0, onIntent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			PendingIntent off = PendingIntent.getBroadcast(context, 0,
					offIntent, PendingIntent.FLAG_UPDATE_CURRENT);

			RemoteViews rv = new RemoteViews(context.getPackageName(),
					R.layout.lights_widget);
			rv.setOnClickPendingIntent(R.id.allOn, on);
			rv.setOnClickPendingIntent(R.id.allOff, off);

			ComponentName thisWidget = new ComponentName(context,
					LightsWidget.class);
			AppWidgetManager manager = AppWidgetManager.getInstance(context);
			manager.updateAppWidget(thisWidget, rv);
		}
	}
	
	private static IConnectionResponseListener createListener() {
		return new ConnectionService.IConnectionResponseListener() {
			
			private static final long serialVersionUID = -474406635566297232L;

			public void responseReceived(Object data, boolean success) {
				if (!success) {
					Toast.makeText(gContext, R.string.IO_exception, Toast.LENGTH_LONG).show();
				}
			}
		};
	}

	public static class LightsUpdater extends BroadcastReceiver {

		private static final String LOG_TAG = "LightsWidget";

		public LightsUpdater() {
			super();
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			int action = intent.getExtras().getInt(ACTION_TAG, -1);
			Log.d(LOG_TAG, "Handled intent with action " + action);
			if (action == 1) {
				Log.d(LOG_TAG, "All ON");
				sendAction(context, true);
			} else if (action == 0) {
				Log.d(LOG_TAG, "All OFF");
				sendAction(context, false);
			}
		}
		
		private void sendAction(final Context context, final boolean state) {
			final Loader<Cursor> cl = new CursorLoader(context, LightTable.CONTENT_URI, new String[]{LightTable.COLUMN_LABEL}, null, null, null);
			cl.registerListener(cl.getId(), new OnLoadCompleteListener<Cursor>() {

				public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
					Log.d(LOG_TAG, "Data load complete. Rows: " + data.getCount());
					ArrayList<String> names = new ArrayList<String>(data.getCount());
					boolean cont = data.moveToFirst();
					while (cont) {
						String name = data.getString(data.getColumnIndex(LightTable.COLUMN_LABEL));
						names.add(name);
						cont = data.moveToNext();
					}
					Intent bindIntent = new Intent(context, ConnectionService.class);
					bindIntent.putExtra(ConnectionService.WIDGET_CALL_IP,
							PreferenceManager.getDefaultSharedPreferences(context).getString(Settings.IP, null));
					bindIntent.putExtra(ConnectionService.WIDGET_SWITCH_SENSOR, "Lights");
					bindIntent.putStringArrayListExtra(ConnectionService.WIDGET_SWITCH_SENSOR_NAME, names);
					bindIntent.putExtra(ConnectionService.WIDGET_SWITCH_SENSOR_STATE, state);
					bindIntent.putExtra(ConnectionService.WIDGET_SWITCH_SENSOR_LISTENER, (java.io.Serializable) createListener());
					bindIntent.putExtra(ConnectionService.WIDGET_SELECTION, ConnectionService.LIGHT_WIDGET);
					context.startService(bindIntent);
					cl.unregisterListener(this);
				}
			});
			cl.startLoading();
		}

	}

}
